package com.take.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.take.common.BaseContext;
import com.take.common.R;
import com.take.dto.OrdersDto;
import com.take.entity.OrderDetail;
import com.take.entity.Orders;
import com.take.service.OrderDetailService;
import com.take.service.OrderService;
import com.take.state.OrderState;
import com.take.state.OrderStateEnum;
import com.take.state.OrderStateMachine;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Api(tags = "订单模块")
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @ApiOperation("用户下单")
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        //必传的参数：addressBookId
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @ApiOperation("分页查询订单（顾客，查看自己的订单）")
    @GetMapping("/page")
    public R<Page<OrdersDto>> page(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int pageSize) {
        //初始查询出的对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //实际返回的对象
        Page<OrdersDto> ordersDtoPageInfo = new Page<>();
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        lqw.eq(Orders::getUserId, userId);
        lqw.orderByDesc(Orders::getOrderTime);
        //执行查询
        orderService.page(pageInfo, lqw);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, ordersDtoPageInfo, "records");
        List<OrdersDto> ordersDtoList = pageInfo.getRecords().stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //再查询与当前订单相关联的订单项
            LambdaQueryWrapper<OrderDetail> lqwOrderDetail = new LambdaQueryWrapper<>();
            lqwOrderDetail.eq(OrderDetail::getOrderId, item.getNumber());
            List<OrderDetail> orderDetailList = orderDetailService.list(lqwOrderDetail);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        //填入封装带有订单项的订单
        ordersDtoPageInfo.setRecords(ordersDtoList);

        return R.success(ordersDtoPageInfo);
    }

    @ApiOperation("分页查询订单（卖家，查看全部订单）")
    /**
     * 后台管理订单信息分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public R<Page> list(@RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "5") int pageSize,
                        String number, Integer status, String beginTime, String endTime) {
        log.info("page = {},pageSize = {}", page, pageSize);

        //构造分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number != null && !number.isEmpty(), Orders::getId, number);
        queryWrapper.eq(status != null, Orders::getStatus, status);
        queryWrapper.ge(beginTime != null && !beginTime.isEmpty(), Orders::getOrderTime, beginTime);
        queryWrapper.le(endTime != null && !endTime.isEmpty(), Orders::getOrderTime, endTime);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        orderService.page(pageInfo, queryWrapper);


        //带有订单详情的分页数据放在ordersDtoPageInfo中
        Page<OrdersDto> ordersDtoPageInfo = new Page<>();
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, ordersDtoPageInfo, "records");
        List<OrdersDto> ordersDtoList = pageInfo.getRecords().stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //再查询与当前订单相关联的订单项
            LambdaQueryWrapper<OrderDetail> lqwOrderDetail = new LambdaQueryWrapper<>();
            lqwOrderDetail.eq(OrderDetail::getOrderId, item.getNumber());
            List<OrderDetail> orderDetailList = orderDetailService.list(lqwOrderDetail);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        //填入封装带有订单项的订单
        ordersDtoPageInfo.setRecords(ordersDtoList);


        return R.success(ordersDtoPageInfo);
    }

    /**
     * 派送订单(更改status为3)
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> updateOrder(@RequestBody Orders orders){


        //查询当前订单现在的状态
        Orders currentOrder = orderService.getById(orders.getId());
        Integer statusCode = currentOrder.getStatus();
        OrderStateEnum currentOrderState = OrderStateEnum.values()[statusCode];
        //将订单状态放入状态机
        OrderStateMachine stateMachine = new OrderStateMachine(currentOrderState);
        //【状态机控制状态变化】
        //<!-- 1待付款（默认直接进入2状态），2待派送，3已派送，4已完成，0已取消   -->
        //订单状态的结果
        String resultMsg = "";
        if(orders.getStatus() == 3){
            stateMachine.deliver();
            resultMsg="订单开始派送";
        }else if(orders.getStatus() == 4){
            stateMachine.receive();
            resultMsg="订单已完成";
        }else if(orders.getStatus() == 0){
            stateMachine.cancel();
            resultMsg="订单已取消";
        }else{
            resultMsg="订单状态("+statusCode+")未发生变化";
        }
        //取出状态，更新数据库
        OrderState newState = stateMachine.getCurrentState();
        statusCode = newState.orderStateType().getState();
        // 更新数据库
        //构造update条件构造器
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        //添加过滤条件
        updateWrapper.eq(Orders::getId, orders.getId());
        updateWrapper.set(Orders::getStatus,statusCode); //新状态 statusCode
        orderService.update(updateWrapper);

        return R.success(resultMsg,null);
    }



}